<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="申请人" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单号" prop="serialNum">
        <el-input
          v-model="queryParams.serialNum"
          placeholder="请输入单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="subscribePatternName">
        <el-input
          v-model="queryParams.subscribePatternName"
          placeholder="请输入类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="审批人(多个）" prop="approver">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.approver"-->
      <!--          placeholder="请输入审批人(多个）"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="审批人" prop="approverName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.approverName"-->
      <!--          placeholder="请输入审批人"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="抄送人" prop="copyerName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.copyerName"-->
      <!--          placeholder="请输入抄送人"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:purchase:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:purchase:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:purchase:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['module:purchase:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :border="true" v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键id" align="center" prop="id" />-->
      <!--      <el-table-column label="用户id" align="center" prop="userId" />-->
      <el-table-column label="申请人" align="center" prop="username"/>
      <el-table-column label="状态" align="center" prop="businessStatus">
        <template slot-scope="scope">
          <div v-if="scope.row.businessStatus=='completed'">已完成</div>
          <div v-if="scope.row.businessStatus=='approve'">审批中</div>
          <div v-if="scope.row.businessStatus=='reject'">驳回</div>
          <div v-if="scope.row.businessStatus=='pending'">待审批</div>
        </template>
      </el-table-column>
      <el-table-column label="单号" align="center" width="150px" prop="serialNum"/>
      <!--      <el-table-column label="申请表类型id" align="center" prop="subscribePatternId" />-->
      <!--      <el-table-column label="类型" align="center" width="120px" prop="subscribePatternName" />-->
      <el-table-column label="申请时间" align="center" width="180px" prop="createTime"/>

      <!--      <el-table-column label="审批人(多个）" align="center" prop="approver" />-->
      <el-table-column label="审批人" align="center" prop="approverName"/>
      <!--      <el-table-column label="抄送人id" align="center" prop="copyerId" />-->
      <el-table-column label="抄送人" align="center" prop="copyerName"/>
      <el-table-column label="详情" align="center">
        <template slot-scope="scope">
          <el-button
            @click="product(scope.row)"
          >采购产品
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:purchase:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:purchase:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="110px">
        <!--        <el-form-item label="用户id" prop="userId">-->
        <!--          <el-input v-model="form.userId" placeholder="请输入用户id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="申请人" prop="username" style="width: 400px;">
          <el-input disabled="true" v-model="form.username" placeholder="请输入申请人"/>
        </el-form-item>
        <!--        <el-form-item label="员工" prop="staffName" style="width: 400px" >-->
        <!--          <el-input v-model="form.staffName" placeholder="请输入" >-->
        <!--            <el-button slot="append" @click="openImportUser" >选择</el-button>-->
        <!--          </el-input>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="单号" prop="serialNum" style="width: 400px">-->
        <!--          <el-input v-model="form.serialNum" placeholder="请输入单号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="申请表类型id" prop="subscribePatternId">-->
        <!--          <el-input v-model="form.subscribePatternId" placeholder="请输入申请表类型id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="类型" prop="subscribePatternName" style="width: 400px">
          <el-input disabled="true" v-model="form.subscribePatternName" placeholder="请输入类型"/>
        </el-form-item>
        <el-form-item label="采购产品" prop="subscribePatternName" style="width: 400px">
          <el-button type="primary" @click="addProduct">采购产品</el-button>
        </el-form-item>
        <el-table :border="true" :data="form.purchaseProductList" style="margin-bottom: 10px;">
          <el-table-column type="index" width="55" align="center"/>
          <el-table-column label="产品名称" align="center" prop="productName"/>
          <el-table-column label="产品类型" align="center" prop="productType"/>
          <el-table-column label="单价" align="center" prop="price"/>
          <el-table-column label="新增入库数量" align="center" prop="number">
            <!--            <template slot-scope="scope">-->
            <!--              <el-input v-model="scope.row.number" placeholder="新增入库数量"  style="width: 80px;"></el-input>-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="deleteBtn(scope)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="是否使用模板" prop="typeStatus" style="width: 400px">
          <el-select v-model="form.typeStatus" placeholder="请选择" @change="changeValue">
            <el-option
              v-for="item in ynOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>

          </el-select>
        </el-form-item>
        <!--        <el-form-item label="审批人" prop="approver">-->
        <!--          <el-input v-model="form.approver" placeholder="请输入审批人(多个）" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="审批人姓名" prop="approverName" style="width: 400px">-->
        <!--          <el-input v-model="form.approverName" placeholder="请输入审批人" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="抄送人id" prop="copyerId">-->
        <!--          <el-input v-model="form.copyerId" placeholder="请输入抄送人id" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="抄送人姓名" prop="copyerName" style="width: 400px">-->
        <!--          <el-input v-model="form.copyerName" placeholder="请输入抄送人" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark" style="width: 400px">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <!-- 固定类型-->
      <div v-if="showApproval2">
        <div style="margin-left: 100px"> 审批人：</div>
        <el-steps :active="0" align-center>
          <el-step v-for="(item,index) in approvalOptions" :key="index" :title="item.nickName"
                   description="就不批"></el-step>
        </el-steps>
        <div style="margin-left: 100px">抄送人:</div>
        <div style="margin-left: 200px">

          <el-avatar v-for="(item,index) in copyerOptions" :key="index"> {{ item.nickName.substr(0, 1) }}</el-avatar>

        </div>
      </div>
      <div v-if="showApproval3">
        <div style="margin-left: 30px">
          <span>请选择审批人</span>
          <el-select @change="changeuseroptions" v-model="value1" multiple placeholder="请选择">
            <el-option
              v-for="item in userlistoptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>

          </el-select>
          <!--          <el-input v-model="approver.userName" style="width: 300px">-->
          <!--            -->
          <!--            <template slot="append">-->
          <!--              <el-button type="primary"  @click="openUser(1)">-->
          <!--                选择审批人-->
          <!--              </el-button>-->
          <!--            </template>-->
          <!--          </el-input>-->
        </div>
        <div style="margin-left: 30px;margin-top: 10px">
          <span style="margin-right: 5px">请选择抄送人</span>
          <el-input v-model="copyer.userName" style="width: 300px">
            <template slot="append">
              <el-button type="primary" @click="openUser(2)">
                选择抄送人
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-user ref="user" @showUser="showUser"></import-user>
    <Elselect @meiye="myfn" @anme="anmefn" @chongzhi="czfn" @serch="serchfn" @dangqian="dqfn" ref="import"
              :list="staffList"></Elselect>
    <importAddProduct ref="importAddProduct" @showAddProduct="showAddProduct"></importAddProduct>


    <el-dialog title="采购产品" :visible.sync="productShow" width="60%" append-to-body>
      <el-table :border="true" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column label="产品名称" align="center" prop="productName"/>
        <el-table-column label="产品类型" align="center" prop="productType"/>
        <el-table-column label="数量" align="center" prop="number"/>
        <el-table-column label="价格" align="center" prop="price"/>
        <el-table-column label="仓库" align="center" prop="warehouseName"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase} from "@/api/module/purchase";
import {getDicts} from "@/api/system/dict/data";
import importUser from '@/views/dialog/user.vue';
import Elselect from "@/components/ELselect/Elselect"
import {listStaff} from "@/api/module/staff";
import {getSubscribepattern} from "@/api/module/subscribepattern";
import {listType} from "@/api/module/type";
import {getuserList, getuserrank} from "@/api/system/user";
import importAddProduct from '@/views/module/outbound/addProduct'


export default {
  name: "Purchase",
  components: {
    importUser,
    Elselect,
    importAddProduct,

  },
  data() {
    return {
      productShow: false,
      productList: [],
      ynOptions: [],
      staffList: [],
      showApprove: false,//查看进度
      showApproval2: false,//模板
      showApproval3: false,//自定义模板
      approvalOptions: [],
      copyer: {},
      copyerOptions: [],
      approver: {},//自定义审批人
      bizReceiptProductList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请表格数据
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        userId:null,
        pageNum: 1,
        pageSize: 10,
        userId: null,
        username: null,
        status: null,
        serialNum: null,
        subscribePatternId: null,
        subscribePatternName: null,
        approver: null,
        approverName: null,
        copyerId: null,
        copyerName: null,
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {},
      value1: [],
      userlistoptions: []
    };
  },
  created() {
    this.getList();
    this.getYesNo()
    this.getrankuser()
    this.form.typeStatus='是'
  },
  methods: {
    // 查询主管级别用户
    getrankuser() {
      getuserrank({rank: "主管", pageSize: 1000}).then(res => {
        this.userlistoptions = res.rows
      })
    },
    changeuseroptions(val) {
      this.form.approverName = null
      val.forEach(ids => {
        this.userlistoptions.forEach(item => {
          if (ids == item.userId) {
            if (this.form.approverName == null) {
              this.form.approverName = item.userName
            } else {
              this.form.approverName = this.form.approverName + ',' + item.userName
            }
          }
        })
      })
    },
    product(value) {
      console.log(value)
      this.productList = value.purchaseProductList
      this.productShow = true
    },
    /** 选择新增入库*/
    addProduct() {
      // console.log('11')
      this.$refs.importAddProduct.show()
    },
    /** 选择采购产品*/
    showAddProduct(value) {
      console.log(value)
      // this.bizReceiptProductList.push(value)
      // console.log(this.form.bizReceiptProductList)
      this.form.purchaseProductList.push(value)
      console.log(this.form.purchaseProductList)
    },
    /** 选购产品删除*/
    deleteBtn(value) {
      this.form.bizReceiptProductList.splice(value.$index, 1)
    },
    /** 选择是否需要模板*/
    async changeValue(val) {
      console.log(val,this.form)
      if (val == '0') {
        /** 进度条展示*/
        this.showApproval2 = false
        this.showApproval3 = false
        this.value1 = []
        this.copyer = {}
      } else {
        //  自定义类型
        this.showApproval2 = false
        this.showApproval3 = true
      }
    },
    /** 打开审批人 */
    openUser(val) {
      this.$refs.user.show(val, 1)
    },
    /** 打开user弹框*/
    openImportUser() {
      this.$refs.import.show()
    },
    /** 组件搜索功能*/
    async serchfn(val) {
      this.queryParams.name = val
      const res = await listStaff(this.queryParams)
      this.staffList = res.rows
    },
    async dqfn(val) {
      this.queryParams.pageNum = val
      const res = await listStaff(this.queryParams)
      // console.log(res.rows)
      this.staffList = res.rows
    },
    async myfn(val) {
      console.log(val)
      this.queryParams.pageSize = val
      const res = await listStaff(this.queryParams)
      // console.log(res.rows)
      this.staffList = res.rows
    },
    /** 组件重置*/
    async czfn() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        username: null,
        trainingItems: null,
        sponsor: null,
        sponsorDept: null,
        participant: null,
        participantDept: null,
        initiateTime: null,
        startTime: null,
        endTime: null,
        days: null,
        status: null,
        tenantId: null,
        staffId: null,
        staffName: null,
      }
      const res = await listStaff(this.queryParams)
      this.staffList = res.rows
      // this.listDatafn()
    },
    anmefn(val) {
      console.log(val)
      this.form.staffName = val.name
      this.form.staffId = val.id
      console.log(this.form)
      this.$refs.import.visible = false
    },
    showUser(data) {
      console.log(data)
      if (data.type == '1') {
        this.approver = data

        //自定义类型赋值
        this.form.approver = data.userId
        this.form.approverName = data.userName
      }
      if (data.type == '2') {
        this.copyer = data
        this.form.copyerId = data.userId
        this.form.copyerName = data.userName
      }
    },
    //是或否
    getYesNo() {
      getDicts('yesorno').then(res => {
        this.ynOptions = res.data
      })
    },
    /**  跟据对应审批 获取相应的申请类型-------更改申请类型*/
    //根据对应审批，获取相应的申请类型————————————————————————————------------更改申请类型
    async getapproverTpye() {
      let res = await getSubscribepattern(8)
      console.log('申请类型', res.data)
      this.form.subscribePatternName = res.data.patternName
      this.form.subscribePatternId = res.data.id
    },
    /** 查询采购申请列表 */
    getList() {
      this.loading = true;
      this.queryParams.userId=this.$store.getters.id;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.value1 = [],
        this.copyer = {},
        this.form = {
          id: null,
          userId: null,
          username: null,
          status: null,
          serialNum: null,
          subscribePatternId: null,
          subscribePatternName: null,
          approver: null,
          approverName: null,
          typeStatus:'0',
          copyerId: null,
          copyerName: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          purchaseProductList: []
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.form.username = this.$store.getters.name
      this.form.userId = this.$store.getters.id
      // this.form.staffId=this.$store.getters.staffId
      // this.form.staffName=this.$store.getters.staffName
      // await this.getapproverTpye()
      const res = await listStaff(this.queryParams)
      this.staffList = res.rows
      this.open = true;
      this.title = "添加采购申请";
      this.$refs.import.unit = res.total
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data;
        if (this.form.typeStatus == '1'){
          this.showApproval3=true;
          let array=this.form.approver.split(',')
          array.forEach(item=>{
            this.value1.push(Number(item))
          })
          this.copyer.userName=this.form.copyerName
        }
        this.open = true;
        this.title = "修改采购申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.approver = this.value1.join(',')
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购申请编号为"' + ids + '"的数据项？').then(function () {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
